﻿using System;
using System.Collections.Generic;
using System.Text;
using LeePong.Game.Entities;

namespace LeePong.Game.Engines
{
    public class VirtualPlayer
    {
        static Random rnd = new Random();
        private Engine _engine;
        private PlayerProfile _profile;

        public VirtualPlayer(Engine engine, PlayerProfile profile)
        {
            _engine = engine;
            _profile = profile;
        }

        public void Move()
        {
            var land = _engine.Land;
            var ball = _engine.Ball;
            var leftRacket = _engine.LeftRacket;

            if (ball.Angle > -90 && ball.Angle < 90)
            {
                var dist = land.Rect.CenterY - leftRacket.Rect.CenterY;
                leftRacket.Rect.CenterY = leftRacket.Rect.CenterY + (dist * _profile.MoveSpeed);
            }
            else
            {
                var dist = ball.Rect.CenterY - leftRacket.Rect.CenterY;
                leftRacket.Rect.CenterY = leftRacket.Rect.CenterY + (dist * _profile.MoveSpeed);
            }
        }

        public void Shoot()
        {
            var ball = _engine.Ball;
            ball.Speed = ball.Speed + ball.Speed * _profile.Power;
            var shot = _profile.GetShot();
            ApplyShot(shot);

        }

        private void ApplyShot(Shot shot)
        {
            var land = _engine.Land;
            var ball = _engine.Ball;

            switch (shot)
            {
                case Shot.Reflect:
                    ball.ReflectAngle();
                    break;
                case Shot.Counter:
                    ball.InvertAngle();
                    break;
                case Shot.Long:
                    ball.Angle = rnd.Next(-5, 5);
                    break;

                case Shot.Cross:
                    ball.Speed = ball.Speed + (_profile.Power * 0.5f);

                    var cibleDx = land.Rect.Right - _engine.LeftRacket.Rect.Width;
                    var cibleDy = ball.Rect.CenterY < land.Rect.CenterY ? land.Rect.Bottom - ball.Rect.CenterY : land.Rect.Top - ball.Rect.CenterY;

                    var dist = Math.Sqrt(Math.Pow(cibleDx, 2) + Math.Pow(cibleDy, 2));
                    var sinAngle = cibleDy / dist;

                    var a = Math.Asin(sinAngle);
                    var angle2 = (a / Math.PI) * 180;

                    ball.Angle = (int)Math.Round(angle2);
                    break;
                default:
                    ball.ReflectAngle();
                    break;
            }
        }
    }
}
